﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SGRapidForm.Common;
using System.Configuration;
using System.Data;
using SGRapidForm.Permission.Entity;
using SGRapidForm.Permission.Service.Interface;

namespace SGDemo.Web
{
    public partial class Main : System.Web.UI.Page
    {
        public const string ContextKey = "SGRapidForm.Common.ApplicationContext";

        private IPermissionService _permissionService = ServiceProxyFactory.Create<IPermissionService>("permissionservice");

        protected void Page_Load(object sender, EventArgs e)
        {
            JSManager.RegAjax(Header, this.GetType().BaseType);
            if (!this.IsPostBack)
            {
                rptModules.DataSource = _permissionService.User_GetModuleBy(ApplicationContext.Current.UserKeyid);
                rptModules.DataBind();
                hlnkRealName.Text = ApplicationContext.Current.RealName.Trim();
                hlnkCurrentDept.Text = ApplicationContext.Current.CurrentDeptName.Trim();
            }
        }

        protected List<PageEntity> GetPagesByModuleKeyid(string moduleKeyid)
        {
            return _permissionService.User_GetPageBy(ApplicationContext.Current.UserKeyid, moduleKeyid);
        }

        protected List<PageEntity> GetSecondStagePageBy(string parentKeyid)
        {
            return _permissionService.User_GetSecondStagePageBy(ApplicationContext.Current.UserKeyid, parentKeyid);
        }

        protected bool GetVisible(string parentKeyid)
        {
            return _permissionService.User_GetSecondStagePageBy(ApplicationContext.Current.UserKeyid, parentKeyid).Count>0;
        }

        /// <summary>
        /// 更改密码
        /// </summary>
        /// <param name="oldPassword">旧密码</param>
        /// <param name="newPassword">新密码</param>
        /// <returns></returns>
        [AjaxPro.AjaxMethod]
        public bool ChangePassword(string oldPassword, string newPassword)
        {
            UserDetails user =  _permissionService.User_GetByKeyid(ApplicationContext.Current.UserKeyid);
            if (user.Password == DESEncrypt.Encrypt(oldPassword))
            {
                //user.Password = DESEncrypt.Encrypt(newPassword.Trim());
                //return _permissionService.User_Update(user);  
                return _permissionService.User_ChangePassword(ApplicationContext.Current.UserKeyid, DESEncrypt.Encrypt(newPassword.Trim()));
            }
            return false;
        }

        /// <summary>
        /// 重新登录
        /// </summary>
        [AjaxPro.AjaxMethod]
        public void Relogin()
        {
            ApplicationContext.Current = null;
            HttpContext.Current.Session[ContextKey] = null;
            HttpContext.Current.Session.Abandon();
        }

        /// <summary>
        /// 获取个人资料
        /// </summary>
        /// <returns></returns>
        [AjaxPro.AjaxMethod]
        public string GetProfile()
        {
            string result = string.Format("UserName:'{0}', RealName:'{1}', MobilePhone:'{2}', Email:'{3}'", ApplicationContext.Current.UserName, ApplicationContext.Current.RealName, ApplicationContext.Current.MobilePhone, ApplicationContext.Current.Email);
            return string.Concat("{",result,"}");
        }

        /// <summary>
        /// 保存个人资料
        /// </summary>
        [AjaxPro.AjaxMethod]
        public bool SaveProfile(string realName, string mobilePhone, string email)
        {
           UserDetails user = _permissionService.User_GetByKeyid(ApplicationContext.Current.UserKeyid);
          
           user.Realname = (realName == null ? "" : realName);
           user.MobilePhone = (mobilePhone == null ? "" : mobilePhone);
           user.Email = (email == null ? "" : email);
           ApplicationContext.Current.RealName = user.Realname;
           ApplicationContext.Current.MobilePhone = user.MobilePhone;
           ApplicationContext.Current.Email = user.Email;

           return _permissionService.User_Update(user);
        }

        [AjaxPro.AjaxMethod]
        public string GetOldPasswordQuestion()
        {
            return ApplicationContext.Current.PasswordQuestion;
        }

        [AjaxPro.AjaxMethod]
        public bool SavePasswordSecurity(string oldPassword, string newPasswordQuestion, string newPasswordAnswer)
        {
            if (ApplicationContext.Current.PasswordAnswer == oldPassword.Trim())
            {
                UserDetails user = _permissionService.User_GetByKeyid(ApplicationContext.Current.UserKeyid);
                user.PasswordAnswer = (newPasswordAnswer == null ? "" : newPasswordAnswer);
                ApplicationContext.Current.PasswordAnswer = user.PasswordAnswer;
                user.PasswordQuestion = (newPasswordQuestion == null ? "" : newPasswordQuestion);
                ApplicationContext.Current.PasswordQuestion = user.PasswordQuestion;
                return _permissionService.User_Update(user);
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 重新登录
        /// </summary>
        public void btnRelogin_Relogin(object sender, EventArgs e)
        {
            HttpContext.Current.Session[ContextKey] = null;
            ClearClientPageCache();
            Response.Redirect("~/Login.aspx");
        }

        public void btnLoginout_Loginout(object sender, EventArgs e)
        {
            HttpContext.Current.Session[ContextKey] = null;
            ClearClientPageCache();
            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "$.closeCurrentWindow()", true);
        }

        public void ClearClientPageCache()
        {
            //清除浏览器缓存 
            Response.Buffer = true;
            Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
            Response.Cache.SetExpires(DateTime.Now.AddDays(-1));
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
            Response.Cache.SetNoStore();
        }

    }
}